<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Activity\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Component\UserComponent;
use Media\Component\AlbumComponent;
use Media\Component\PhotoComponent;
use Mark\Component\MarkPhotoComponent;
use Mark\Component\LikePhotoComponent;
use Media\Component\VideoComponent;
use Mark\Component\MarkVideoComponent;
use Mark\Component\LikeVideoComponent;
use Application\Component\CommentComponent;
use Media\Component\UserAlbumComponent;
use Activity\Component\ActivityComponent;
use Media\Entity\Album;
use Media\Entity\UserAlbum;
use Zend\View\Model\JsonModel;
use Exception;
use Activity\Entity\PhotoActivity;
use Activity\Entity\VideoActivity;
use DateTime;
use Activity\Entity\CommentActivity;

class ActivityController extends AbstractActionController
{

    protected $em;

    protected $baseURL;

    protected $userComponent;
    protected $activityComponent;
    protected $photoActivityComponent;
    protected $photoComponent;
    protected $markPhotoComponent;
    protected $likePhotoComponent;
    protected $videoActivityComponent;
    protected $videoComponent;
    protected $markVideoComponent;
    protected $likeVideoComponent;
    protected $commentComponent;
    
    protected $authservice;
    protected $user;

    public function init()
    {
        if (null === $this->em) {
            $this->user = $this->identity();
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
            $this->userComponent = new UserComponent($this->em);
            $this->activityComponent = $this->getServiceLocator()->get('ActivityComponent');//new ActivityComponent($this->em);
            $this->markPhotoComponent = new MarkPhotoComponent($this->em);
            $this->likePhotoComponent = new LikePhotoComponent($this->em);
            $this->photoComponent = new PhotoComponent($this->em);
            $this->markVideoComponent = new MarkVideoComponent($this->em);
            $this->likeVideoComponent = new LikeVideoComponent($this->em);
            $this->videoComponent = new VideoComponent($this->em);
            $this->commentComponent = new CommentComponent($this->em);
            //var_dump($this->markPhotoComponent->getStats(1));
            //var_dump($this->markPhotoComponent->getStats(2));
        }
        $this->baseURL = "http://localhost/passenger/public/";
        return $this->em;
    }

    public function getSpecificConfig()
    {
        $config = $this->getServiceLocator()->get('Config');
        return $config['entity']['user']['attribute'];
    }
    
    public function testAction(){
        $this->init();
        
        try {
            $photo = $this->photoComponent->get(1);
            $photoActivity = new PhotoActivity();
            $photoActivity->photo = $photo;
            $photoActivity->user = $this->identity();
            $photoActivity->date = new DateTime("now");
            $this->activityComponent->insert($photoActivity);
            
            $comment = $this->commentComponent->get(1);
            $commentActivity = new CommentActivity();
            $commentActivity->comment = $comment;
            $commentActivity->user = $this->identity();
            $commentActivity->date = new DateTime("now");
            $this->activityComponent->insert($commentActivity);
            
        	$activities = $this->activityComponent->listAll(); 
        	$message = array(
        			'success' => 'Activities successfully load. ',
        	        'user'=>$this->identity(),
        	        'activities'=>$activities
        	);
        } catch (Exception $e) {
        	$message = array(
        			'exception' => $e->getTraceAsString()
        	);
        }
        return new JsonModel($message);
    }
    
    public function listAction(){
    	$this->init();
    	$maxId = (int)$this->params()->fromRoute('id', 0);
    	$limit = (int)$this->params()->fromRoute('limit', '5');//100;//
        $user = $this->identity();
    	//try {
    		$adapter = $this->getServiceLocator()->get('db-adapter');
    		$fromDate = null;
    		$toDate = null;
    		$activities = $this->activityComponent->listFromMax($adapter, $user!=null?$user->uid:0, $maxId, "public", $limit);
    		$feeds = array();
    		$total = 0;
    		foreach ($activities as $row) {
    		    $parsed = $this->parseRow($row);
    		    if($parsed!=null) $feeds[] = $parsed;
    		    $total++;
    		}
    		$message = array(
    			'success' => 'Activities successfully load. ',
    		    'user'=>$this->user,
    			'feed'=>$feeds,
    		    'now'=>(new DateTime("now"))->format("Y-m-d H:i:s"),
    		    "total"=>$total,
    		);
    	/*} catch (Exception $e) {
    		$message = array(
    				'exception' => $e->getTraceAsString()
    		);
    	}*/
    	return new JsonModel($message);
    }
    public function listFromMinAction(){
    	$this->init();
    	$minId = (int)$this->params()->fromRoute('id', 0);
    	$limit = (int)$this->params()->fromRoute('limit', '5');//100;//
        $user = $this->identity();
    	try {
    		$adapter = $this->getServiceLocator()->get('db-adapter');
    		$activities = $this->activityComponent->listFromMin($adapter, $user!=null?$user->uid:0, $minId, "public", $limit);
    		$feeds = array();
    		$total = 0;
    		foreach ($activities as $row) {
    		    $parsed = $this->parseRow($row);
    		    if($parsed!=null) $feeds[] = $parsed;
    		    $total++;
    		}
    		$message = array(
    			'success' => 'Activities successfully load. ',
    		    'user'=>$this->identity(),
    			'feed'=>$feeds,
    		    'now'=>(new DateTime("now"))->format("Y-m-d H:i:s"),
    		    "total"=>$total,
    		);
    	} catch (Exception $e) {
    		$message = array(
    				'exception' => $e->getTraceAsString()
    		);
    	}
    	return new JsonModel($message);
    }
    
    public function parseRow($row){
        if($row==null ||!isset($row["type"])) return null;
        if($row["type"]=="photo_activity"){
            $stats = $this->markPhotoComponent->getStats($row["photo_id"]);
            $nb_marks = ($stats==null||count($stats)==0||!isset($stats[0]["nb"])||$stats[0]["nb"]==null)?0:((int)$stats[0]["nb"]);//TODO Compter
            $total_marks = ($stats==null||count($stats)==0||!isset($stats[0]["total"])||$stats[0]["total"]==null)?0:((int)$stats[0]["total"]);//TODO Compter
            $avg_marks = $nb_marks>0?(((int)($total_marks*10/$nb_marks))/10):0;
            $photo = $this->photoComponent->get($row["photo_id"]);
            $userRow = $photo->user_uid;//$this->userComponent->get($row["uid"]);
            $result = array(
            	"type"=>$row["type"],
                "id"=>$row["id"],
                "created_at"=>$row["created_at"],
                "date"=>$row["date"],
                "user"=>$userRow->getJson()
            );
            if($photo!=null) {
                $myLike = ($this->user==null)?null:$this->likePhotoComponent->getLikePhotoByUser($photo->id, $this->user->uid);
                $nbLikes = $this->likePhotoComponent->getNb($photo->id);
                $result["photo"] = $photo->getJson();
                $result["photo"]["nb_marks"] = $nb_marks;
                $result["photo"]["avg_marks"] = $avg_marks;
                $result["photo"]["i_like"] = ($myLike!=null);
                $result["photo"]["nb_likes"] = $nbLikes;
            }
            
            return $result;
        }
        else if($row["type"]=="video_activity"){
            $stats = $this->markVideoComponent->getStats($row["video_id"]);
            $nb_marks = ($stats==null||count($stats)==0||!isset($stats[0]["nb"])||$stats[0]["nb"]==null)?0:((int)$stats[0]["nb"]);//TODO Compter
            $total_marks = ($stats==null||count($stats)==0||!isset($stats[0]["total"])||$stats[0]["total"]==null)?0:((int)$stats[0]["total"]);//TODO Compter
            $avg_marks = $nb_marks>0?(((int)($total_marks*10/$nb_marks))/10):0;
            $video = $this->videoComponent->get($row["video_id"]);
            $userRow = $video->user_uid;//$this->userComponent->get($row["uid"]);
            $result = array(
            	"type"=>$row["type"],
                "id"=>$row["id"],
                "created_at"=>$row["created_at"],
                "date"=>$row["date"],
                "user"=>$userRow->getJson()
            );
            if($video!=null) {
                $myLike = ($this->user==null)?null:$this->likeVideoComponent->getLikeVideoByUser($video->id, $this->user->uid);
                $nbLikes = $this->likeVideoComponent->getNb($video->id);
                $result["video"] = $video->getJson();
                $result["video"]["count_marks"] = $nb_marks;
                $result["video"]["avg_marks"] = $avg_marks;
                $result["video"]["i_like"] = ($myLike!=null);
                $result["video"]["count_likes"] = $nbLikes;
            }
            return $result;
        }
        else if($row["type"]=="mark_activity"){
            $markPhotoActivity = $this->markPhotoComponent->getByMarkId($row["mark_id"]);
            $markVideoActivity = $this->markVideoComponent->getByMarkId($row["mark_id"]);
            if($markPhotoActivity!=null && $markPhotoActivity->photo!=null && $markPhotoActivity->mark!=null && $markPhotoActivity->mark->user!=null){
                $stats = $this->markPhotoComponent->getStats($markPhotoActivity->photo->id);
                $nb_marks = ($stats==null||count($stats)==0||!isset($stats[0]["nb"])||$stats[0]["nb"]==null)?0:((int)$stats[0]["nb"]);//TODO Compter
                $total_marks = ($stats==null||count($stats)==0||!isset($stats[0]["total"])||$stats[0]["total"]==null)?0:((int)$stats[0]["total"]);//TODO Compter
                $avg_marks = $nb_marks>0?(((int)($total_marks*10/$nb_marks))/10):0;
                $myLike = ($this->user==null)?null:$this->likePhotoComponent->getLikePhotoByUser($markPhotoActivity->photo->id, $this->user->uid);
                $nbLikes = $this->likePhotoComponent->getNb($markPhotoActivity->photo->id);
                $photoJson = $markPhotoActivity->photo->getJson();
                $photoJson["nb_marks"] = $nb_marks;
                $photoJson["avg_marks"] = $avg_marks;
                $photoJson["i_like"] = ($myLike!=null);
                $photoJson["nb_likes"] = $nbLikes;
                $result = array(
                		"type"=>$row["type"],
                		"id"=>$row["id"],
                		"created_at"=>$row["created_at"],
                		"date"=>$row["date"],
                		"user"=>$markPhotoActivity->mark->user->getJson(),
                		"photo"=>$photoJson,
                );
                return $result;
            }
            else if($markVideoActivity!=null && $markVideoActivity->video!=null && $markVideoActivity->mark!=null && $markVideoActivity->mark->user!=null){
                $stats = $this->markVideoComponent->getStats($markVideoActivity->video->id);
                $nb_marks = ($stats==null||count($stats)==0||!isset($stats[0]["nb"])||$stats[0]["nb"]==null)?0:((int)$stats[0]["nb"]);//TODO Compter
                $total_marks = ($stats==null||count($stats)==0||!isset($stats[0]["total"])||$stats[0]["total"]==null)?0:((int)$stats[0]["total"]);//TODO Compter
                $avg_marks = $nb_marks>0?(((int)($total_marks*10/$nb_marks))/10):0;
                $myLike = ($this->user==null)?null:$this->likeVideoComponent->getLikeVideoByUser($markVideoActivity->video->id, $this->user->uid);
                $nbLikes = $this->likeVideoComponent->getNb($markVideoActivity->video->id);
                $videoJson = $markVideoActivity->video->getJson();
                $videoJson["count_marks"] = $nb_marks;
                $videoJson["avg_marks"] = $avg_marks;
                $videoJson["i_like"] = ($myLike!=null);
                $videoJson["count_likes"] = $nbLikes;
                $result = array(
                		"type"=>$row["type"],
                		"id"=>$row["id"],
                		"created_at"=>$row["created_at"],
                		"date"=>$row["date"],
                		"user"=>$markVideoActivity->mark->user->getJson(),
                		"video"=>$videoJson,
                );
                return $result;
            }
        }
        else if($row["type"]=="like_activity"){
            $likePhotoActivity = $this->likePhotoComponent->getByLikeId($row["like_id"]);
            $likeVideoActivity = $this->likeVideoComponent->getByLikeId($row["like_id"]);
            if($likePhotoActivity!=null && $likePhotoActivity->photo!=null && $likePhotoActivity->like!=null && $likePhotoActivity->like->user!=null){
                $stats = $this->markPhotoComponent->getStats($likePhotoActivity->photo->id);
                $nb_marks = ($stats==null||count($stats)==0||!isset($stats[0]["nb"])||$stats[0]["nb"]==null)?0:((int)$stats[0]["nb"]);//TODO Compter
                $total_marks = ($stats==null||count($stats)==0||!isset($stats[0]["total"])||$stats[0]["total"]==null)?0:((int)$stats[0]["total"]);//TODO Compter
                $avg_marks = $nb_marks>0?(((int)($total_marks*10/$nb_marks))/10):0;
                $myLike = ($this->user==null)?null:$this->likePhotoComponent->getLikePhotoByUser($likePhotoActivity->photo->id, $this->user->uid);
                $nbLikes = $this->likePhotoComponent->getNb($likePhotoActivity->photo->id);
                $photoJson = $likePhotoActivity->photo->getJson();
                $photoJson["nb_marks"] = $nb_marks;
                $photoJson["avg_marks"] = $avg_marks;
                $photoJson["i_like"] = ($myLike!=null);
                $photoJson["nb_likes"] = $nbLikes;
                $result = array(
                		"type"=>$row["type"],
                		"id"=>$row["id"],
                		"created_at"=>$row["created_at"],
                		"date"=>$row["date"],
                		"user"=>$likePhotoActivity->like->user->getJson(),
                		"photo"=>$photoJson,
                );
                return $result;
            }
            else if($likeVideoActivity!=null && $likeVideoActivity->video!=null && $likeVideoActivity->like!=null && $likeVideoActivity->like->user!=null){
                $stats = $this->markVideoComponent->getStats($likeVideoActivity->video->id);
                $nb_marks = ($stats==null||count($stats)==0||!isset($stats[0]["nb"])||$stats[0]["nb"]==null)?0:((int)$stats[0]["nb"]);//TODO Compter
                $total_marks = ($stats==null||count($stats)==0||!isset($stats[0]["total"])||$stats[0]["total"]==null)?0:((int)$stats[0]["total"]);//TODO Compter
                $avg_marks = $nb_marks>0?(((int)($total_marks*10/$nb_marks))/10):0;
                $myLike = ($this->user==null)?null:$this->likeVideoComponent->getLikeVideoByUser($likeVideoActivity->video->id, $this->user->uid);
                $nbLikes = $this->likeVideoComponent->getNb($likeVideoActivity->video->id);
                $videoJson = $likeVideoActivity->video->getJson();
                $videoJson["count_marks"] = $nb_marks;
                $videoJson["avg_marks"] = $avg_marks;
                $videoJson["i_like"] = ($myLike!=null);
                $videoJson["count_likes"] = $nbLikes;
                $result = array(
                		"type"=>$row["type"],
                		"id"=>$row["id"],
                		"created_at"=>$row["created_at"],
                		"date"=>$row["date"],
                		"user"=>$likeVideoActivity->like->user->getJson(),
                		"video"=>$videoJson,
                );
                return $result;
            }
        }
        return null;
    }
    
    public function viewAction(){
    	$this->init();
        $user = $this->identity();
    	/*try {*/
    		
    		$adapter = $this->getServiceLocator()->get('db-adapter');
    		$fromDate = null;
    		$toDate = null;
    		//friend_of_friend
    		$activities = $this->activityComponent->listActivities($adapter, $user!=null?$user->uid:0, $fromDate, $toDate, "public");
    		
    		foreach ($activities as $row) {
    			//echo $row->id;
    			var_dump($row);echo "<hr/>";
    		}
    		
    		$message = array(
    				'success' => 'Activities successfully load. ',
    				//'db-adapter'=>$this->getServiceLocator()->get('db-adapter'),
    				//'user'=>$this->identity(),
    				'activities'=>$activities
    		);
    	/*} catch (Exception $e) {
    		$message = array(
    				'exception' => $e->getTraceAsString()
    		);
    	}*/
    	return new JsonModel($message);
    }

    

}
